package com.digitalchina.lxnsy.activity.old;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessPlan;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.PlanOptsOrgVO;
import com.digitalchina.lxnsy.entity.PlantTypeVO;
import com.digitalchina.lxnsy.entity.ProductPlanListVO;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/8/21 15:07
 * 修改备注：
 * ================================================
 */
public class AddStandardProductionActivity extends BaseActivity {

    @Bind(R.id.cb_vegetables)
    CheckBox cbVegetables;
    @Bind(R.id.cb_fruiter)
    CheckBox cbFruiter;
    @Bind(R.id.tv_crop)
    TextView tvCrop;
    @Bind(R.id.layout_crop)
    RelativeLayout layoutCrop;
    @Bind(R.id.tv_time_or_type)
    TextView tvTimeOrType;
    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.layout_time)
    RelativeLayout layoutTime;
    @Bind(R.id.tv1)
    TextView tv1;
    @Bind(R.id.et_area)
    EditText etArea;
    @Bind(R.id.layout_area)
    RelativeLayout layoutArea;
    @Bind(R.id.tv_mode)
    TextView tvMode;
    @Bind(R.id.layout_mode)
    RelativeLayout layoutMode;
    @Bind(R.id.tv2)
    TextView tv2;
    @Bind(R.id.et_age)
    EditText etAge;
    @Bind(R.id.layout_age)
    RelativeLayout layoutAge;
    @Bind(R.id.tv_city)
    TextView tvCity;
    @Bind(R.id.layout_city)
    RelativeLayout layoutCity;
    @Bind(R.id.tv_company)
    TextView tvCompany;
    @Bind(R.id.layout_company)
    RelativeLayout layoutCompany;

    private String planTypeCode = "3001002"; // 计划类型CODE 果树（3001001） 蔬菜（3001002）
    private String cropTypeCode = ""; // 农作物信息Code
    private String cropKindCode = ""; // 农作物品种Code
    private String seedDate = ""; // 播种时间 2018-08-22 蔬菜时必填
    private String treeAge = ""; // 树龄 果树必填
    private String plantSize = ""; // 种植面积
    private String plantTypeCode = ""; // 栽培方式CODE 蔬菜时必填
    private String provinceName = ""; // 省名称
    private String cityName = ""; // 城市名称
    private String countyName = ""; // 区名称
    private String suitOrgId = ""; // 所属单位Id
    private String productStandardId = ""; // 生产标准Id
    private String farmOperationId = ""; // 农事操作阶段name
    private String productStandardName = ""; // 生产标准name
    private String farmOperationName = ""; // 农事操作阶段ID
    private String planId = ""; // 生产计划ID（修改时，传入）


    private List<PlanOptsOrgVO> orgList = new ArrayList<>(); // 企业
    private List<PlantTypeVO.BusinessDataBean> vegetableCropType = new ArrayList<>(); // 蔬菜
    private List<PlantTypeVO> fruitKinds = new ArrayList<>(); // 果树
    private List<PlantTypeVO.BusinessDataBean> plantType = new ArrayList<>(); // 栽培方式

    private Map<String, String> map = new HashMap<>();

    //选择器
    private OptionsPickerView pvOrg, pvCropVegetable, pvCropFruit, pvCropFruit2, pvMode;
    private int mYear, mMonth, mDayOfMonth;//播种时间  年月日

    private int index = -1; // 标记当选择为果树时 记录农作物信息的下标

    private ProductPlanListVO vo = null;
    private List<String> emptyList = new ArrayList<>();

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_add_standard_production);
        setTitle("获取作物种植标准");
    }

    @Override
    public void initMember() {

        emptyList.add("");

        BusinessPlan.getOpts(this, mHandler);

        if (getIntent().hasExtra("ProductPlanListVO")) {
            vo = (ProductPlanListVO) getIntent().getSerializableExtra("ProductPlanListVO");
            if (vo != null)
                setView();
        }

    }

    // 修改时 渲染页面
    private void setView() {

        planId = vo.getId();
        planTypeCode = vo.getPlanType().getCode();
        cropTypeCode = vo.getCropType().getCode();

        if (vo.getProvince() != null)
            provinceName = vo.getProvince().getName();
        if (vo.getCity() != null)
            cityName = vo.getCity().getName();
        if (vo.getCounty() != null)
            countyName = vo.getCounty().getName();


        tvCrop.setText(vo.getCropType().getName());

        if (planTypeCode.equals("3001002")) {
            //蔬菜
            cbVegetables.setChecked(true);
            cbFruiter.setChecked(false);
            //栽培方式
            layoutMode.setVisibility(View.VISIBLE);
            layoutAge.setVisibility(View.GONE);
            // 播种时间
            tvTime.setText(DateUtil.getDate(vo.getSeedDate(), DateStyle.YYYY_MM_DD));
            //栽培方式
            if (vo.getPlantType() != null) {
                plantTypeCode = vo.getPlantType().getCode();
                tvMode.setText(vo.getPlantType().getName() + "");
            }
        } else {
            //果树
            cbVegetables.setChecked(false);
            cbFruiter.setChecked(true);
            layoutMode.setVisibility(View.GONE);
            //树龄
            layoutAge.setVisibility(View.VISIBLE);
            // 农作物品种
            if (vo.getKindType() != null) {
                tvTime.setText(vo.getKindType().getName());
                cropKindCode = vo.getKindType().getCode();
            }


            etAge.setText(vo.getTreeAge() + "");
        }

        // 面积
        etArea.setText(vo.getPlantSize() + "");

        tvCity.setText(vo.getFullAddress() + "");
        if (vo.getSuitOrg() != null) {
            suitOrgId = vo.getSuitOrg().getId();
            tvCompany.setText(vo.getSuitOrg().getName() + "");
        }


//        if (vo.getProductStandard() != null) {
//            productStandardId = vo.getProductStandard().toString();
//        }
//        if (vo.getFarmOperation() != null) {
//            farmOperationId = vo.getFarmOperation().getId();
//            farmOperationName = vo.getFarmOperation().getFarmName();
//        }


    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case MSG.MSG_GET_PLAN_OPTS_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_PLAN_OPTS_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        orgList = FastJsonUtil.getListBean(object.toString(), "orgList", PlanOptsOrgVO.class);
        vegetableCropType = FastJsonUtil.getListBean(object.toString(), "vegetableCropType", PlantTypeVO.BusinessDataBean.class);
        fruitKinds = FastJsonUtil.getListBean(object.toString(), "fruitKinds", PlantTypeVO.class);
        plantType = FastJsonUtil.getListBean(object.toString(), "plantType", PlantTypeVO.BusinessDataBean.class);


        pvOrg = new OptionsPickerView.Builder(AddStandardProductionActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                String select = orgList.get(options1).getName();
                suitOrgId = orgList.get(options1).getId();
                tvCompany.setText(select);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvOrg.setPicker(orgList);

        pvCropVegetable = new OptionsPickerView.Builder(AddStandardProductionActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                String select = vegetableCropType.get(options1).getName();
                cropTypeCode = vegetableCropType.get(options1).getCode();
                tvCrop.setText(select);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvCropVegetable.setPicker(vegetableCropType);


        // 农作物品种  二级果树分类
        pvCropFruit2 = new OptionsPickerView.Builder(AddStandardProductionActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                if (fruitKinds.get(index).getBusinessDataList() == null || fruitKinds.get(index).getBusinessDataList().size() <= 0)
                    return;
                String select = fruitKinds.get(index).getBusinessDataList().get(options1).getName();
                cropKindCode = fruitKinds.get(index).getBusinessDataList().get(options1).getCode();
                tvTime.setText(select);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();


        // 农作物信息
        pvCropFruit = new OptionsPickerView.Builder(AddStandardProductionActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                String select = fruitKinds.get(options1).getBusinessData().getName();
                index = options1;
                if (fruitKinds.get(index).getBusinessDataList() == null || fruitKinds.get(index).getBusinessDataList().size() == 0)
                    pvCropFruit2.setPicker(emptyList);
                else
                    pvCropFruit2.setPicker(fruitKinds.get(index).getBusinessDataList());
                cropTypeCode = fruitKinds.get(options1).getBusinessData().getCode();
                tvCrop.setText(select);
                // 二级分类清空
                tvTime.setText("");
                cropKindCode = "";
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvCropFruit.setPicker(fruitKinds);


        pvMode = new OptionsPickerView.Builder(AddStandardProductionActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                String select = plantType.get(options1).getName();
                plantTypeCode = plantType.get(options1).getCode();
                tvMode.setText(select);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvMode.setPicker(plantType);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_crop, R.id.layout_time, R.id.layout_mode, R.id.layout_city, R.id.layout_company, R.id.bt_next, R.id.cb_vegetables, R.id.cb_fruiter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_crop:

                if (vegetableCropType == null || fruitKinds == null || vegetableCropType.size() <= 0 || fruitKinds.size() <= 0) {
                    showToast("正在获取农作物信息");
                } else {
                    if (cbVegetables.isChecked())
                        pvCropVegetable.show();
                    else
                        pvCropFruit.show();
                }
                break;
            case R.id.layout_time:
                if (cbVegetables.isChecked())
                    showDatePicker();
                else {
                    if (index == -1)
                        showToast("请先选择农作物信息");
                    else
                        pvCropFruit2.show();
                }
                break;
            case R.id.layout_mode:
                pvMode.show();
                break;
            case R.id.layout_city:
                showAddressPicker();
                break;
            case R.id.layout_company:
                if (plantType == null || plantType.size() <= 0)
                    showToast("正在获取企业信息");
                else
                    pvOrg.show();
                break;
            case R.id.cb_vegetables:
                setCheckBox(0);
                break;
            case R.id.cb_fruiter:
                setCheckBox(1);
                break;
            case R.id.bt_next:
                next();

                break;
        }
    }

    // 下一步
    private void next() {
        if (StringUtil.isTextEmpty(tvCrop)) {
            showToast("请选择农作物信息");
            return;
        }

        seedDate = tvTime.getText().toString();
        treeAge = etAge.getText().toString();

        if (cbVegetables.isChecked()) {
            //蔬菜
            if (StringUtil.isStrEmpty(seedDate)) {
                showToast("请选择播种时间");
                return;
            }
            if (StringUtil.isTextEmpty(tvMode)) {
                showToast("请选择栽培方式");
                return;
            }
        } else {
            //果树
            if (StringUtil.isTextEmpty(tvTime)) {
                showToast("请选择农作物品种");
                return;
            }
            if (StringUtil.isStrEmpty(treeAge)) {
                showToast("请填写树龄");
                return;
            }
        }

        plantSize = etArea.getText().toString();
        if (StringUtil.isStrEmpty(plantSize)) {
            showToast("请填写面积");
            return;
        }
        if (StringUtil.isTextEmpty(tvCity)) {
            showToast("请选择所在区域");
            return;
        }
        if (StringUtil.isTextEmpty(tvCompany)) {
            showToast("请选择所属企业");
            return;
        }


        map.put("planTypeCode", planTypeCode);
        map.put("cropTypeCode", cropTypeCode);
        map.put("cropKindCode", cropKindCode);
        map.put("seedDate", seedDate);
        map.put("treeAge", treeAge);
        map.put("plantSize", plantSize);
        map.put("plantTypeCode", plantTypeCode);
        map.put("provinceName", provinceName);
        map.put("cityName", cityName);
        map.put("countyName", countyName);
        map.put("suitOrgId", suitOrgId);
        map.put("planId", planId);

        GotoUtil.gotoForResultActivity(AddStandardProductionActivity.this, SelectProductionActivity.class, 198, "map", map);
    }

    /**
     * 蔬菜果树选择
     *
     * @param i
     */
    private void setCheckBox(int i) {

        tvCrop.setText("");
        tvTime.setText("");
        tvMode.setText("");
        etAge.setText("");

        if (i == 0) {
            cbVegetables.setChecked(true);
            cbFruiter.setChecked(false);
            tvTimeOrType.setText("播种时间");
            layoutMode.setVisibility(View.VISIBLE);
            layoutAge.setVisibility(View.GONE);
            planTypeCode = "3001002";
        } else {
            cbFruiter.setChecked(true);
            cbVegetables.setChecked(false);
            tvTimeOrType.setText("农作物品种");
            layoutMode.setVisibility(View.GONE);
            layoutAge.setVisibility(View.VISIBLE);
            planTypeCode = "3001001";
        }
    }

    /**
     * 所在区域选择
     */
    private void showAddressPicker() {
        final BottomDialog bottomDialog = new BottomDialog(AddStandardProductionActivity.this);
        bottomDialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(Province province, City city, County county, Street street) {
                provinceName = province.province_name;
                cityName = city != null && !city.city_name.equals("县") ? city.city_name : "";
                countyName = county != null ? county.county_name : "";
                tvCity.setText(String.format("%s %s %s", provinceName, cityName, countyName));
                bottomDialog.dismiss();
            }
        });
        bottomDialog.show();
    }


    /**
     * 显示日期选择
     */
    private void showDatePicker() {

        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                String selectDate = year + "-" + (month + 1) + "-" + dayOfMonth;
                tvTime.setText(selectDate);
            }
        }, mYear, mMonth, mDayOfMonth);

//        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() - 1000);
        datePickerDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

}
